import 'package:agora_rtc_engine/src/binding_forward_export.dart';
import 'package:flutter/services.dart';

class MediaRecorderOhosImpl implements MediaRecorder {
  MediaRecorderOhosImpl._(){
    recorderMethodChannel = const MethodChannel("agora_rtc_ng/media_recorder");
    recorderMethodChannel.setMethodCallHandler((call) async {
      if (call.method == 'onRecorderStateChanged') {
        print("agora_rtc_ng callHandler onRecorderStateChanged ${call.arguments
            .toString()}");
        int state = int.parse(call.arguments['state']);
        RecorderState stateType = RecorderState.recorderStateError;
        for (var e in RecorderState.values) {
          if (e.value() == state) {
            stateType = e;
            break;
          }
        }
        int reason = int.parse(call.arguments['reason']);
        RecorderReasonCode reasonType = RecorderReasonCode.recorderReasonNone;
        for (var e in RecorderReasonCode.values) {
          if (e.value() == reason) {
            reasonType = e;
            break;
          }
        }
        _eventHandler?.onRecorderStateChanged?.call(
            call.arguments['channelId'], int.parse(call.arguments['uid']),
            stateType, reasonType);
        return true;
      } else if (call.method == 'onRecorderInfoUpdated') {
        print("agora_rtc_ng callHandler onRecorderInfoUpdated ${call.arguments
            .toString()}");
        String info = call.arguments['info'];
        RecorderInfo recorderInfo = RecorderInfo.fromJson(jsonDecode(info));
        _eventHandler?.onRecorderInfoUpdated?.call(
            call.arguments['channelId'], int.parse(call.arguments['uid']),
            recorderInfo);
        return true;
      }
      return false;
    });
  }

  late MethodChannel recorderMethodChannel;
  MediaRecorderObserver? _eventHandler;

  MediaRecorderOhosImpl.create()
      : this._();

  @override
  Future<void> setMediaRecorderObserver(MediaRecorderObserver callback) async {
    _eventHandler = callback;
  }

  @override
  Future<void> startRecording(MediaRecorderConfiguration config) async {
    final Map<String, dynamic> args = {
      "config": jsonEncode(config.toJson()),
    };
    recorderMethodChannel.invokeMethod("RtcEngine_startRecording", args);
  }

  @override
  Future<void> stopRecording() async {
    recorderMethodChannel.invokeMethod("RtcEngine_stopRecording");
  }
}
